package com.pope.framework.triage.modular.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pope.framework.constants.CompareEnum;
import com.pope.framework.core.reqres.response.ResponseData;
import com.pope.framework.dict.modular.entity.DictCompare;
import com.pope.framework.dict.modular.entity.DictConsciousState;
import com.pope.framework.dict.modular.entity.DictExamination;
import com.pope.framework.dict.modular.entity.DictNorm;
import com.pope.framework.dict.modular.entity.DictSicknessGrade;
import com.pope.framework.dict.modular.service.DictCompareService;
import com.pope.framework.dict.modular.service.DictConsciousStateService;
import com.pope.framework.dict.modular.service.DictExaminationService;
import com.pope.framework.dict.modular.service.DictNormService;
import com.pope.framework.dict.modular.service.DictSicknessGradeService;
import com.pope.framework.kernel.model.exception.ServiceException;
import com.pope.framework.triage.modular.dto.AutoCompareGradeDto;
import com.pope.framework.triage.modular.dto.GradeCompareDto;
import com.pope.framework.triage.modular.dto.PatientInfoDto;
import com.pope.framework.triage.modular.dto.ValueDto;
import com.pope.framework.triage.modular.entity.GradeInfo;
import com.pope.framework.triage.modular.entity.GradeNorm;
import com.pope.framework.triage.modular.entity.PatientInfo;
import com.pope.framework.triage.modular.service.GradeInfoService;
import com.pope.framework.triage.modular.service.GradeNormService;
import com.pope.framework.triage.modular.service.PatientInfoService;
import com.pope.framework.triage.modular.vo.GradeInfoVo;
import com.pope.framework.triage.modular.vo.GradeNormVo;
import com.pope.framework.triage.modular.vo.PatientInfoVo;
import com.pope.framework.triage.modular.vo.TriageSimpleInfoVo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.Example;
import io.swagger.annotations.ExampleProperty;

@RestController
//@CrossOrigin(allowCredentials="true",maxAge = 3600)
@CrossOrigin
@RequestMapping("${spring.application.app-id}/grade")
@Api(value="分级设置相关API",tags= {"分级设置相关API"})
public class GradeInfoController {
	@Autowired
	private GradeInfoService gradeInfoService;
	@Autowired
	private GradeNormService gradeNormService;
	@Autowired
	private DictNormService dictNormService;
	@Autowired
	private DictCompareService dictCompareService;
	@Autowired
	private DictExaminationService dictExaminationService;
	@Autowired
	private DictSicknessGradeService dictSicknessGradeService;
	@Autowired
	private DictConsciousStateService dictConsciousStateService;
	@ApiOperation(value = "获取级别信息列表",notes = "获取级别信息列表")
	@ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "Integer",paramType = "query",example = "1")
	
	@ApiResponse(code=1,message="返回对象",response=TriageSimpleInfoVo.class,responseContainer="List")
	@GetMapping("list")
	public ResponseData<List<GradeInfo>> list(Integer hospitalId){
		GradeInfo queryGradeInfo=new GradeInfo();
//		if(hospitalId!=null) {
//			queryGradeInfo.setHospitalId(hospitalId);
//		}
		QueryWrapper<GradeInfo> queryGradeInfoWrapper=new QueryWrapper<>();
		queryGradeInfoWrapper.setEntity(queryGradeInfo);
		List<GradeInfo> data=gradeInfoService.list(queryGradeInfoWrapper);
		return ResponseData.success(data);
	}

	
	@ApiOperation(value = "根据ID获取级别信息",notes = "根据ID获取级别信息")
    @ApiImplicitParam(name = "id",value = "患者ID主键",dataType = "Integer",paramType = "path",example = "1112",required=true)
	@GetMapping("{id}")
	public ResponseData<GradeInfoVo> select(@PathVariable Integer id){
		if(id==null) {
			throw new ServiceException("级别ID不能为空，请重新确认！");
		}
		
		GradeInfo gradeInfo=gradeInfoService.getById(id);
		if(gradeInfo==null) {
			throw new ServiceException("该级别信息不存在，请重新确认!");
		}
		GradeInfoVo gradeInfoVo=new GradeInfoVo();
		BeanUtil.copyProperties(gradeInfo, gradeInfoVo);
		gradeInfoVo.setGradeNorms(getGradeNorm(gradeInfo));
		gradeInfoVo.setGradeNormString(getGradeNormString(gradeInfoVo.getGradeNorms()));
		return ResponseData.success(gradeInfoVo);
	}
	
	private List<GradeNormVo>  getGradeNorm(GradeInfo gradeInfo) {
		DictNorm queryDictNorm=new DictNorm();
		QueryWrapper<DictNorm> queryDictNormWrapper=new QueryWrapper<>();
		queryDictNormWrapper.setEntity(queryDictNorm);
		queryDictNormWrapper.orderByAsc("orders");
		List<DictNorm> dictNorms=dictNormService.list(queryDictNormWrapper);
		
		DictCompare queryDictCompare=new DictCompare();
		QueryWrapper<DictCompare> queryDictCompareWrapper=new QueryWrapper<>();
		queryDictCompareWrapper.setEntity(queryDictCompare);
		queryDictCompareWrapper.orderByAsc("orders");
		List<DictCompare> dictCompares=dictCompareService.list(queryDictCompareWrapper);
 		
		GradeNorm queryGradeNorm=new GradeNorm();
		queryGradeNorm.setGradeId(gradeInfo.getId());
		QueryWrapper<GradeNorm> queryGradeNormWrapper=new QueryWrapper<>();
		queryGradeNormWrapper.setEntity(queryGradeNorm);
		List<GradeNorm> gradeNorms=gradeNormService.list(queryGradeNormWrapper);
		List<GradeNormVo> newGradeNorms=CollUtil.newArrayList();
		if(CollUtil.isNotEmpty(dictNorms) && CollUtil.isNotEmpty(gradeNorms)) {
			for(DictNorm dictNorm:dictNorms) {
				for(GradeNorm gradeNorm:gradeNorms) {
					if(dictNorm.getCode().equals(gradeNorm.getNormId())) {
						GradeNormVo gradeNormVo=new GradeNormVo();
						BeanUtil.copyProperties(gradeNorm, gradeNormVo);
						gradeNormVo.setNormName(dictNorm.getName());
						gradeNormVo.setUnit(dictNorm.getUnit());
						if(CollUtil.isNotEmpty(dictCompares)) {
							for(DictCompare dictCompare:dictCompares) {
								if(dictCompare.getCode().equals(gradeNorm.getCompare())) {
									gradeNormVo.setCompareName(dictCompare.getName());
									break;
								}
							}
						}
						newGradeNorms.add(gradeNormVo);
					}
				}
			}
		}
		return newGradeNorms;
	}
	
	private String getGradeNormString(List<GradeNormVo> gradeNorms) {
		Map<String,List<GradeNormVo>> groupGradeNorm=CollUtil.newHashMap();
		Map<String,BigDecimal> mapValueDto=CollUtil.newHashMap();
		for(GradeNormVo gradeNorm:gradeNorms) {//体征公式数据
			if(groupGradeNorm.containsKey(gradeNorm.getNormId())) {
				groupGradeNorm.get(gradeNorm.getNormId()).add(gradeNorm);
			}else {
				groupGradeNorm.put(gradeNorm.getNormId(), CollUtil.newArrayList());
				groupGradeNorm.get(gradeNorm.getNormId()).add(gradeNorm);
			}
		}
		String name="";
		for(Map.Entry<String,List<GradeNormVo>> map:groupGradeNorm.entrySet()) {
			if(StrUtil.isNotBlank(name)) {
				name+="或";
			}
			List<GradeNormVo> values=map.getValue();
			String subName="";
			if(CollUtil.isNotEmpty(values)) {
				for(GradeNormVo gradeNormVo:values) {
					if(StrUtil.isNotBlank(subName)) {
						subName+="与";
					}
					subName+=gradeNormVo.getNormName();
					if(CompareEnum.RANGE_ALL_CLOSE.getCode().equals(gradeNormVo.getCompare())
							||CompareEnum.RANGE_ALL_OPEN.getCode().equals(gradeNormVo.getCompare())
							||CompareEnum.RANGE_LEFT_OPEN.getCode().equals(gradeNormVo.getCompare())
							||CompareEnum.RANGE_RIGHT_OPEN.getCode().equals(gradeNormVo.getCompare())) {
						if(CompareEnum.RANGE_ALL_CLOSE.getCode().equals(gradeNormVo.getCompare())) {
							subName+=CompareEnum.GT_EQ.getName()+gradeNormVo.getValue1()
							+gradeNormVo.getUnit();
							subName+="与";
							subName+=CompareEnum.LT_EQ.getName()+gradeNormVo.getValue2()+gradeNormVo.getUnit();
						}else if(CompareEnum.RANGE_ALL_OPEN.getCode().equals(gradeNormVo.getCompare())) {
							subName+=CompareEnum.GT.getName()+gradeNormVo.getValue1()
							+gradeNormVo.getUnit();
							subName+="与";
							subName+=CompareEnum.LT.getName()+gradeNormVo.getValue2()+gradeNormVo.getUnit();
						}else if(CompareEnum.RANGE_LEFT_OPEN.getCode().equals(gradeNormVo.getCompare())) {
							subName+=CompareEnum.GT_EQ.getName()+gradeNormVo.getValue1()
							+gradeNormVo.getUnit();
							subName+="与";
							subName+=CompareEnum.LT.getName()+gradeNormVo.getValue2()+gradeNormVo.getUnit();
						}else if(CompareEnum.RANGE_RIGHT_OPEN.getCode().equals(gradeNormVo.getCompare())) {
							subName+=CompareEnum.GT.getName()+gradeNormVo.getValue1()
							+gradeNormVo.getUnit();
							subName+="与";
							subName+=CompareEnum.LT_EQ.getName()+gradeNormVo.getValue2()+gradeNormVo.getUnit();
						}
					}else {
						subName+=gradeNormVo.getCompareName()+gradeNormVo.getValue1()+gradeNormVo.getUnit();
					}
				}
				if(StrUtil.isNotBlank(subName)) {
					subName="("+subName+")";
				}
			}
			name+=subName;
		}
		return name;
	}
	@ApiOperation(value = "添加分级信息",notes = "添加分级信息")
	@ApiImplicitParam(required=true,name="gradeInfoVo",dataType="GradeInfoVo", paramType="body",examples = @Example({
        @ExampleProperty(value = "{'user':'id'}", mediaType = "application/json")
    }))
	@PostMapping("")
	public ResponseData<Integer> add(@RequestBody GradeInfoVo gradeInfoVo){
		if(gradeInfoVo==null) {
			throw new ServiceException("存储对象为NULL，请重写确认！");
		}
		gradeInfoVo.setId(null);
		Integer id=this.gradeInfoService.insert(gradeInfoVo);
		return ResponseData.success(id);
	}
	
	@ApiOperation(value = "修改分级记录",notes = "修改分级记录")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id",value = "分级ID主键",dataType = "Integer",paramType = "path",example = "1112",required=true)
		,
		@ApiImplicitParam(required=true,name="gradeInfoVo",dataType="GradeInfoVo", paramType="body",examples = @Example({
	        @ExampleProperty(value = "{'user':'id'}", mediaType = "application/json")
	    }))
	})
	
	@PutMapping("{id}")
	public ResponseData<String> update(@PathVariable("id") Integer id,@RequestBody GradeInfoVo gradeInfoVo){		
		if(id==null) {
			throw new ServiceException("主键ID不能为null");
		}
		if(gradeInfoVo==null) {
			throw new ServiceException("存储对象为NULL，请重写确认！");
		}
		gradeInfoVo.setId(id);
		this.gradeInfoService.modify(gradeInfoVo);
		return ResponseData.success();
	}
	@ApiOperation(value = "根据ID删除分级",notes = "根据ID删除分级")
    @ApiImplicitParam(name = "id",value = "分级ID主键",dataType = "Integer",paramType = "path",example = "1112",required=true)
	@DeleteMapping("{id}")
	public ResponseData<String> delete(@PathVariable("id") Integer id){	
		if(id==null) {
			throw new ServiceException("主键ID不能为null");
		}
		this.gradeInfoService.delete(id);
		return ResponseData.success();
	}
	
//	@ApiOperation(value = "获取自动分级信息",notes = "根据生命体征信息获取自动分级数据")
//	@PostMapping("compare")
//	public ResponseData<GradeInfoVo> compare(@RequestBody GradeCompareDto gradeCompareDto){	
//		if(gradeCompareDto==null) {
//			throw new ServiceException("生命体征对象不能为空");
//		}
//		GradeInfo gradeInfo=this.gradeInfoService.compare(gradeCompareDto);
//		GradeInfoVo gradeInfoVo=new GradeInfoVo();
//		if(gradeInfo==null) {
//			return ResponseData.success(gradeInfoVo);
//		}
//		BeanUtil.copyProperties(gradeInfo, gradeInfoVo);
//		gradeInfoVo.setGradeNorms(this.getGradeNorm(gradeInfo));
//		gradeInfoVo.setGradeNormString(this.getGradeNormString(gradeInfoVo.getGradeNorms()));
//		return ResponseData.success(gradeInfoVo);
//	}

	@ApiOperation(value = "自动分级（新）",notes = "自动分级（新）")
	@PostMapping("autoCompare")
	public ResponseData<GradeInfoVo> autoCompare(@RequestBody AutoCompareGradeDto autoCompareGradeDto,Integer hospitalId){
		if(autoCompareGradeDto==null) {
			return ResponseData.success(null);
		}
		//最大检伤等级
		Integer maxExamination=0;
		if(CollUtil.isNotEmpty(autoCompareGradeDto.getExaminations())) {
			QueryWrapper<DictExamination> queryWrapper=new QueryWrapper<>();
			queryWrapper.select("MAX(GRADE) AS grade");
			queryWrapper.in("CODE", autoCompareGradeDto.getExaminations());
			Map<String,Object> data=dictExaminationService.getMap(queryWrapper);
			maxExamination=Convert.toInt(data.get("grade"), 0);
		}
		//意识状态
		Integer maxConsciousState=0;
		if(StrUtil.isNotBlank(autoCompareGradeDto.getConsciousState())) {
			DictConsciousState queryDictConsciousState=new DictConsciousState();
			queryDictConsciousState.setCode(autoCompareGradeDto.getConsciousState());
			QueryWrapper<DictConsciousState> queryWrapper=new QueryWrapper<>();
			queryWrapper.setEntity(queryDictConsciousState);
			List<DictConsciousState> datas=dictConsciousStateService.list(queryWrapper);
			if(CollUtil.isNotEmpty(datas)) {
				maxConsciousState=Convert.toInt(datas.get(0).getGrade(),0);
			}
		}
		Integer maxSicknessGrade=0;
		if(StrUtil.isNotBlank(autoCompareGradeDto.getSicknessGrade())) {
			DictSicknessGrade queryDictSicknessGrade=new DictSicknessGrade();
			queryDictSicknessGrade.setCode(autoCompareGradeDto.getSicknessGrade());
			QueryWrapper<DictSicknessGrade> queryWrapper=new QueryWrapper<>();
			queryWrapper.setEntity(queryDictSicknessGrade);
			List<DictSicknessGrade> datas=dictSicknessGradeService.list(queryWrapper);
			if(CollUtil.isNotEmpty(datas)) {
				maxSicknessGrade=Convert.toInt(datas.get(0).getGrade(),0);
			}
		}
		int[] value={maxExamination,maxConsciousState,maxSicknessGrade};
		Integer max=NumberUtil.max(value);;
		GradeInfo queryGradeInfo=new GradeInfo();
		queryGradeInfo.setDanger(max);
//		if(hospitalId!=null) {
//			queryGradeInfo.setHospitalId(hospitalId);
//		}
		QueryWrapper<GradeInfo> queryGradeInfoWrapper=new QueryWrapper<>();
		queryGradeInfoWrapper.setEntity(queryGradeInfo);
		GradeInfo gradeInfo=gradeInfoService.getOne(queryGradeInfoWrapper);
		if(gradeInfo==null) {
			return ResponseData.success();
			//throw new ServiceException("该级别信息不存在，请重新确认!");
		}
		GradeInfoVo gradeInfoVo=new GradeInfoVo();
		BeanUtil.copyProperties(gradeInfo, gradeInfoVo);
		gradeInfoVo.setGradeNorms(getGradeNorm(gradeInfo));
		gradeInfoVo.setGradeNormString(getGradeNormString(gradeInfoVo.getGradeNorms()));
		return ResponseData.success(gradeInfoVo);
	}
	
	
	
	@ApiOperation(value = "根据级别编号获取自动分级信息",notes = "根据级别编号获取自动分级信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "hospitalId",value = "所在医院ID",dataType = "Integer",paramType = "query",example = "1112",required=true),
		@ApiImplicitParam(name = "danger",value = "分级编码",dataType = "Integer",paramType = "query",example = "1112",required=true),
	})
	@GetMapping("compare")
	public ResponseData<GradeInfoVo> compare(Integer hospitalId,Integer danger){	
//		if(hospitalId==null) {
//			throw new ServiceException("所在医院ID不能为空");
//		}
		if(danger==null) {
			throw new ServiceException("分级编号不能为空");
		}
		GradeInfo queryGradeInfo=new GradeInfo();
		queryGradeInfo.setDanger(danger);
//		if(hospitalId!=null) {
//			queryGradeInfo.setHospitalId(hospitalId);
//		}
		QueryWrapper<GradeInfo> queryGradeInfoWrapper=new QueryWrapper<>();
		queryGradeInfoWrapper.setEntity(queryGradeInfo);
		GradeInfo gradeInfo=gradeInfoService.getOne(queryGradeInfoWrapper);
		if(gradeInfo==null) {
			return ResponseData.success();
			//throw new ServiceException("该级别信息不存在，请重新确认!");
		}
		GradeInfoVo gradeInfoVo=new GradeInfoVo();
		BeanUtil.copyProperties(gradeInfo, gradeInfoVo);
		gradeInfoVo.setGradeNorms(getGradeNorm(gradeInfo));
		gradeInfoVo.setGradeNormString(getGradeNormString(gradeInfoVo.getGradeNorms()));
		return ResponseData.success(gradeInfoVo);
		//return ResponseData.success(gradeInfoService.getOne(queryGradeInfoWrapper));
//		GradeInfo gradeInfo=this.gradeInfoService.compare(gradeCompareDto);
//		GradeInfoVo gradeInfoVo=new GradeInfoVo();
//		if(gradeInfo==null) {
//			return ResponseData.success(gradeInfoVo);
//		}
//		BeanUtil.copyProperties(gradeInfo, gradeInfoVo);
//		gradeInfoVo.setGradeNorms(this.getGradeNorm(gradeInfo));
//		gradeInfoVo.setGradeNormString(this.getGradeNormString(gradeInfoVo.getGradeNorms()));
//		return ResponseData.success(gradeInfoVo);
	}
}
